package com.example.juc.controller;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.*;

/**
 * @author jl
 * @since 2021/10/9 21:10
 */
public class ABADemo {
    private static AtomicStampedReference<Integer> a = new AtomicStampedReference<>(100, 1); // 初始值，版本号

    public static void main(String[] args) {
        new Thread(() -> {
            int stamp = a.getStamp();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ;
            a.compareAndSet(100, 101, stamp, stamp + 1);
            a.compareAndSet(101, 100, a.getStamp(), a.getStamp() + 1);
        }).start();

        int stamp = a.getStamp();
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ;
        boolean result = a.compareAndSet(100, 200, stamp, stamp + 1);
        System.out.println("result = " + result + " , 值 = " + a.getReference() + " , 版本号 = " + a.getStamp());
    }
}